package test.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class NettyClient {
    public static void main(String[] args) {
        EventLoopGroup workgroup = new NioEventLoopGroup();
        NettyClientHandler clientHandler = new NettyClientHandler();
        try {
            Bootstrap b = new Bootstrap();
            b.group(workgroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new ByteArrayDecoder());
                            pipeline.addLast(new ByteArrayEncoder());
                            pipeline.addLast(clientHandler);
                        }
                    });
            // 同步连接
            ChannelFuture f = b.connect("127.0.0.1", 19001).sync();
            System.out.println(">>> 客户端已连接到 ");
            String message = "ABC";
            byte[] bytes = message.getBytes(StandardCharsets.UTF_8);
            for (int i = 0; i < 10; i++) {
                 clientHandler.sendMessageWithInt(bytes.length);
                 clientHandler.sendMessageWithBytes(bytes);
            }

            // 等待关闭信号（服务端或自己）
            f.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
